<template>
  <div class="app-container">

    <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="110px"
      style="width: 670px; margin-left:50px;">

      <el-form-item :label="$t('Coupon_name')" prop="name">
        <el-input v-model="dataForm.name" />
      </el-form-item>

      <!--       <el-form-item :label="$t('分发类型')" prop="type">-->
      <!--         <el-select v-model="dataForm.type" disabled @change="handleChangeType">-->
      <!--           <el-option-->
      <!--             v-for="type in typeOptions"-->
      <!--             :key="type.value"-->
      <!--             :label="type.label"-->
      <!--             :value="type.value"/>-->
      <!--         </el-select>-->
      <!--       </el-form-item>-->
      <!--       <el-form-item :label="$t('Introduction')" prop="desc">-->
      <!--         <el-input v-model="dataForm.desc"/>-->
      <!--       </el-form-item>-->
      <!--       <el-form-item :label="$t('Label')" prop="tag">-->
      <!--         <el-input v-model="dataForm.tag"/>-->
      <!--       </el-form-item>-->
      <el-form-item :label="$t('优惠券图片')" prop="pictureUrl">
        <el-upload :headers="headers" :action="uploadPath" :show-file-list="false" :on-success="uploadPicUrl"
          :on-remove="handleGoodsPicRemove" class="avatar-uploader" accept=".jpg,.jpeg,.png,.gif">
          <img v-if="dataForm.pictureUrl" :src="dataForm.pictureUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
          <label v-if="dataForm.pictureUrl" class="el-upload-list__item-status-label avatar-uploader__status_label"
            @click.stop="handleGoodsPicRemove()"><i class="el-icon-delete"></i></label>
        </el-upload>
      </el-form-item>
      <!--        <el-form-item v-if="dataForm.type != 3" :label="$t('使用门槛')" prop="userLevel" >-->
      <!--          <el-checkbox-group v-model="dataForm.userLevel" @change="nolimit">-->
      <!--            <el-checkbox :label="0" >{{$t('无限制')}}</el-checkbox>-->
      <!--            &lt;!&ndash; <el-checkbox :label="1" >{{$t('白银会员')}}</el-checkbox>-->
      <!--            <el-checkbox :label="2" >{{$t('黄金会员')}}</el-checkbox>-->
      <!--            <el-checkbox :label="3" >{{$t('铂金会员')}}</el-checkbox>-->
      <!--            <el-checkbox :label="4" >{{$t('钻石会员')}}</el-checkbox> &ndash;&gt;-->
      <!--          </el-checkbox-group>-->
      <!--        </el-form-item>-->
      <!--       <el-form-item v-if="dataForm.type != 3" :label="$t('商品活动价共用')" prop="promotionOnly" >-->
      <!--         <el-radio v-model="dataForm.promotionOnly" :label="false">{{$t('共用')}}</el-radio>-->
      <!--         <el-radio v-model="dataForm.promotionOnly" :label="true">{{$t('不共用')}}</el-radio>-->
      <!--       </el-form-item>-->
      <el-form-item :label="$t('Lowest_spending_value')" prop="min">
        <el-input v-model.number="dataForm.min" type="number" :min="0" oninput="if(value<0) value= (-1) * value">
          <template slot="append">{{ $t('Dollars') }}</template>
        </el-input>
      </el-form-item>
      <!-- prop="ranges" -->
      <el-form-item :label="$t('使用范围')">
        <!-- <el-radio v-model="dataForm.ranges" :label="0">{{ $t('通用') }}</el-radio> -->
        <!-- <el-radio v-model="dataForm.ranges" :label="1">{{ $t('APP') }}</el-radio>
        <el-radio v-model="dataForm.ranges" :label="2">{{ $t('POS') }}</el-radio>
        <el-radio v-model="dataForm.ranges" :label="3">{{ $t('网站') }}</el-radio> -->
        <el-checkbox-group v-model="checkList">
          <el-checkbox label="0" @change="changeCheckbox">{{ $t('通用') }}</el-checkbox>
          <el-checkbox label="1" @change="changeCheckbox">{{ $t('APP') }}</el-checkbox>
          <el-checkbox label="2" @change="changeCheckbox">{{ $t('POS') }}</el-checkbox>
          <el-checkbox label="3" @change="changeCheckbox">{{ $t('网站') }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item :label="$t('折扣类型')" prop="discountType">
        <el-radio-group v-model="dataForm.discountType">
          <el-radio :label="1">{{ $t('满减') }}</el-radio>
          <el-radio :label="2">{{ $t('折扣') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="dataForm.discountType == 1" :label="$t('Discount_price')" prop="discount">
        <el-input v-model.number="dataForm.discount" type="number" min="0" oninput="if(value<0) value= (-1) * value">
          <template slot="append">{{ $t('Dollars') }}</template>
        </el-input>
      </el-form-item>
      <el-form-item v-show="dataForm.discountType == 2" :label="$t('折扣')" prop="discountRate">
        <el-input v-model.number="dataForm.discountRate" type="number" min="0"
          oninput="if(value<0) value= (-1) * value">
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('Limited_per_person')" prop="limit">
        <el-input v-model.number="dataForm.limit" type="number" min="0" oninput="if(value<0) value= (-1) * value">
          <template slot="append">{{ $t('Sheets') }}</template>
        </el-input>
      </el-form-item>

      <el-form-item :label="$t('Amount_of_coupons')" prop="total">
        <template slot="label">
          <span>{{ $t('优惠券数量') }}</span>
          <el-popover placement="top-start" title="" trigger="click" :content="$t('默认值为0表示没有限制')">
            <i class="el-icon-question"  slot="reference"></i>
          </el-popover>
        </template>
        <el-input v-model.number="dataForm.total" type="number" min="0" oninput="if(value<0) value= (-1) * value">
        </el-input>
      </el-form-item>

      <el-form-item :label="$t('使用限制')" prop="useLimit">
        <el-select v-model="dataForm.useLimit" :placeholder='$t("请选择")' collapse-tags>
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <span>使用</span>
        <el-input v-if="dataForm.useLimit != 4" v-model.number="dataForm.useLimitNum" type="number"
          style="width: 120px;" @change="changeNum(dataForm.useLimitNum)">
          <template slot="append">{{ $t('张') }}</template>
        </el-input>
      </el-form-item>
      <!--
      <el-form-item :label="$t('有效期')" prop="timeType">
        <el-radio-group v-model="dataForm.timeType">
          <el-radio-button v-if="dataForm.type != 3" :label="0">{{ $t('Respective_days_after_claiming_the_coupon') }}
          </el-radio-button>
          <el-radio-button :label="1">{{ $t('Select_deadline') }}</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="dataForm.timeType === 0" prop="days">
        <el-input v-model.number="dataForm.days" type="number">
          <template slot="append">{{ $t('天') }}</template>
        </el-input>
      </el-form-item> -->

      <el-form-item :label='$t("有效期")' prop="days">
        <el-radio-group v-model="radio">
          <el-radio :label="0">时间范围</el-radio>
          <el-radio :label="1">有效天数</el-radio>
        </el-radio-group>
        <el-date-picker v-show="radio == 0" v-model="value1" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" @change="changeDatePick" style="width:380px"
          value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
        <div v-show="radio == 1">
          {{ $t('有效天数') }}:<el-input style="width:100px" v-model="days" @change="inputDays" type="number" min="1" />
        </div>
      </el-form-item>

      <!-- <el-form-item v-show="dataForm.timeType === 1" prop="startTime">
        <el-date-picker v-model="dataForm.startTime" type="datetime" :placeholder="$t('Select_dates')"
          value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" :picker-options="pickerOptions" />
      </el-form-item>
      <el-form-item v-show="dataForm.timeType === 1" prop="endTime">
        <el-date-picker v-model="dataForm.endTime" type="datetime" :placeholder="$t('Select_dates')"
          value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" :picker-options="pickerOptions" />
      </el-form-item> -->
      <!-- <el-form-item v-show="dataForm.timeType === 1" prop="timeList">
        <el-date-picker v-model="dataForm.timeList" type="datetimerange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" :picker-options="pickerOptions" @change="changeDateTime"
          value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item :label="$t('优惠类型')">
        <el-checkbox :label="1" @change="changeLevelMember">{{ $t('等级会员') }}</el-checkbox>
        <el-select multiple v-model="dataForm.levelMemberType" :disabled="!this.isLevelMember" :placeholder='$t("请选择")'>
          <el-option v-for="item in levelMember" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <br />

        <el-checkbox :label="2" @change="changeMoneyMember">{{ $t('付费会员') }}</el-checkbox>
        <el-select multiple v-model="dataForm.moneyMemberType" :disabled="!this.isMoneyMember" :placeholder='$t("请选择")'>
          <el-option v-for="item in moneyMember" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <br />
      </el-form-item>
      <el-form-item :label="$t('商品限制范围')">
        <el-radio-group v-model="dataForm.goodsType">
          <el-radio-button :label="0">{{ $t('Usable_in_any_situation') }}</el-radio-button>
          <el-radio-button v-if="dataForm.type != 3" :label="1">{{ $t('指定分类') }}</el-radio-button>
          <el-radio-button :label="2">{{ $t('指定商品') }}</el-radio-button>
          <!--            <el-radio-button :label="2">{{$t('Select_merchandise')}}</el-radio-button>-->
        </el-radio-group>
      </el-form-item>

      <el-form-item v-show="dataForm.goodsType === 1" prop="goodsValue">
        <!--          {{$t('Not_supported_at_the_moment')}}-->
        <el-cascader :options="categories" :props="props" v-model="dataForm.goodsValue" :show-all-levels="false"
          collapse-tags clearable>
        </el-cascader>
      </el-form-item>

      <el-form-item v-show="dataForm.goodsType === 2"  prop="detailedGoodsValue">
        <el-select v-model="dataForm.selectGoods" filterable multiple :placeholder='$t("请选择")' collapse-tags style="width: 480px">
          <el-option v-for="item in goodsList" :key="item.key" :label="item.label" :value="item.key">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('区域限制')">
        <el-radio-group v-model="dataForm.areaLimit">
          <el-radio-button :label="0">{{ $t('不限区域') }}</el-radio-button>
          <el-radio-button :label="1">{{ $t('限制区域') }}</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-show="dataForm.areaLimit == 0 ? false : true" prop="regions">
        <el-cascader :options="locations" :props="regionProps" v-model="dataForm.regions" :show-all-levels="false"
          collapse-tags clearable>
        </el-cascader>
      </el-form-item>

      <el-form-item :label="$t('损耗承受单位')">
        <el-radio-group v-model="dataForm.lossBearing">
          <el-radio-button :label="0">{{ $t('总部') }}</el-radio-button>
          <el-radio-button :label="1">{{ $t('门店') }}</el-radio-button>
        </el-radio-group>
      </el-form-item>


      <el-form-item prop="isBirthdayUse">
        <template slot="label">
          <span>{{ $t('生日福利券') }}</span>
          <el-popover placement="top-start" title=""  trigger="click" :content="$t('当它被设置为生日优惠券时，它将在会员生日时自动发放到账户')">
            <i class="el-icon-question"  slot="reference"></i>
          </el-popover>
        </template>
          <!-- <el-tooltip class="item" effect="light"
            content="When it is set up as a birthday coupon, it will be automatically paid to the account on the member's birthday"
            placement="top-start">
            <span> <i class="el-icon-question"></i></span>
          </el-tooltip>
        </template> -->
        <el-radio-group v-model="isBirthdayUse" @change="changeIsBirthdayUse">
          <el-radio :label="0">{{ $t('No') }}</el-radio>
          <el-radio :label="1">{{ $t('Yes') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('Explanation')" prop="useInstruction">
        <el-input type="textarea" v-model="dataForm.useInstruction"></el-input>
      </el-form-item>
    </el-form>
    <div class="op-container">
      <el-button @click="handleBack" style="margin-right: 480px">{{ $t('Back') }}</el-button>
      <el-button v-if="typePage" v-permission="['GET /admin/p/coupon_elec_add']" type="primary" @click="createData">{{
    $t('Confirm')
}}</el-button>
      <el-button v-else type="primary" v-permission="['GET /admin/p/coupon_elec_add']" @click="updateData">
        {{ $t('Confirm') }}</el-button>
    </div>
  </div>
</template>

<script>
import { listCategory } from '../../api/category'
import { listLocationRegion } from '../../api/region'
import { listpPutaway } from '../../api/goods'
import { createCoupon, updateCoupon } from '../../api/coupon'
import { getToken } from '../../utils/auth'
import { uploadPath } from '../../api/storage'
import { levelMemberList, payMemberList } from '../../api/user'

export default {
  name: 'elecCouponCreate',
  data() {
    const defaultTypeOptions = [
      {
        label: this.$t('电子优惠券'),
        value: 1
      }
    ]

    const defaultStatusOptions = [
      {
        label: this.$t('Normal'),
        value: 0
      },
      {
        label: this.$t('Expired'),
        value: 1
      },
      {
        label: this.$t('Merchandise_removed'),
        value: 2
      }
    ]

    const validateDiscount = (rule, value, callback) => {
      let discountType = this.dataForm.discountType
      if (discountType == 1 && value == null) {
        return callback(new Error(this.$t('满减金额不能为空')));
      }

      callback();
    }

    const validateDiscountRate = (rule, value, callback) => {
      let discountType = this.dataForm.discountType
      if (discountType == 2 && !value) {
        return callback(new Error(this.$t('百分比不能为空')));
      }

      callback();
    }
    const validateDays = (rule, value, callback) => {
      if (this.dataForm.startTime && this.dataForm.endTime) {
        callback();
        return;
      }
      else if (this.days) {
        callback();
      }
      else {
        return callback(new Error(this.$t('有效期不能为空')));
      }
    }

    const validateStartTime = (rule, value, callback) => {
      let timeType = this.dataForm.timeType
      if (timeType == 1 && !value) {
        return callback(new Error(this.$t('开始时间不能为空')));
      }

      callback();
    }

    const validateEndTime = (rule, value, callback) => {
      let timeType = this.dataForm.timeType
      if (timeType == 1 && !value) {
        return callback(new Error(this.$t('结束时间不能为空')));
      }

      callback();
    }

    const validateTimeList = (rule, value, callback) => {
      const timeType = this.dataForm.timeType;
      if (!value && timeType == 1) {
        return callback(new Error(this.$t('请选择有效期时间')));
      }
      callback();
    }

    const validateGoodsValue = (rule, value, callback) => {
      let goodsType = this.dataForm.goodsType
      if (goodsType == 1 && value.length == 0) {
        return callback(new Error(this.$t('商品分类不能为空')));
      }
      callback();
    }

    const validateRegions = (rule, value, callback) => {
      let regions = this.dataForm.regions;
      if (this.dataForm.areaLimit == 0) {
        callback();
      }
      if (!regions || regions.length == 0) {
        return callback(new Error(this.$t('区域不能为空')));
      }
      callback();
    }


    return {
      radio: 0,
      days: undefined,
      isLevelMember: false,
      isMoneyMember: false,
      isBirthdayUse: 0,
      uploadPath,
      typeOptions: Object.assign({}, defaultTypeOptions),
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 86400000;
        },
      },
      dataForm: {
        selectGoods: [],
        id: undefined,
        name: undefined,
        desc: undefined,
        tag: undefined,
        total: 1,
        discount: 1,
        discountType: 1,
        discountRate: 100,
        min: 1,
        ranges: [],
        limit: 1,
        type: 1,
        status: 0,
        goodsType: 0,
        goodsValue: [],
        regions: [],
        levelMemberType: [],
        moneyMemberType: [],
        useLimit: '',
        useLimitNum: 1,
        areaLimit: 0,
        lossBearing: 0,
        timeType: 1,
        days: undefined,
        timeList: undefined,
        startTime: null,
        endTime: null,
        userLevel: [0],
        promotionOnly: false,
        country: '',
        province: '',
        city: '',
        pictureUrl: '',
        surplus: 0,
        useInstruction: '',
        isBirthdayUse: 0,
      },
      dialogFormVisible: false,
      dialogStatus: '',
      list: [],
      checkList: [],
      rules: {
        name: [
          { required: true, message: this.$t('Coupon_title_cannot_be_empty'), trigger: 'blur' }
        ],
        discount: [
          { validator: validateDiscount, trigger: 'blur' }
        ],
        discountRate: [
          { validator: validateDiscountRate, trigger: 'blur' }
        ],
        min: [
          { required: true, trigger: 'blur' }
        ],
        limit: [
          { required: true, trigger: 'blur' }
        ],
        total: [
          { required: true, trigger: 'blur' }
        ],
        useLimit: [
          { required: true, trigger: 'change', message: this.$t('用户限制类型不能为空') }
        ],
        useLimitNum: [
          { required: true, trigger: 'blur' }
        ],
        timeType: [
          { required: true, trigger: 'blur' }
        ],
        days: [
          // { required: true, trigger: 'blur' }
          { validator: validateDays, trigger: 'blur' }
        ],
        // startTime: [
        //   { validator: validateStartTime, trigger: 'blur' }
        // ],
        // endTime: [
        //   { validator: validateEndTime, trigger: 'blur' }
        // ],
        // timeList: [
        //   { validator: validateTimeList, trigger: 'blur' }
        // ],
        goodsValue: [
          { validator: validateGoodsValue, trigger: 'blur' }
        ],
        regions: [
          { validator: validateRegions, trigger: 'blur' }
        ],

      },
      value1: 0,
      categories: [],
      locations: [],
      goodsList: [],
      props: { multiple: true, value: 'id', label: 'name', emitPath: false },
      regionProps: { multiple: true, value: 'id', label: 'nameEn', emitPath: false },
      options: [{
        value: 0,
        label: this.$t('每年')
      }, {
        value: 1,
        label: this.$t('每月')
      }, {
        value: 2,
        label: this.$t('每周')
      }, {
        value: 3,
        label: this.$t('每天')
      }, {
        value: 4,
        label: this.$t('不限')
      },
      ],
      levelMember: [{
        value: 0,
        label: this.$t('普通会员')
      }, {
        value: 1,
        label: this.$t('银卡会员')
      }, {
        value: 2,
        label: this.$t('金卡会员')
      }, {
        value: 3,
        label: this.$t('钻石会员')
      }],
      moneyMember: [{
        value: 0,
        label: this.$t('畅享月票会员')
      }, {
        value: 1,
        label: this.$t('畅享年票会员')
      }, {
        value: 2,
        label: this.$t('早餐月票会员')
      }, {
        value: 3,
        label: this.$t('早餐年票会员')
      }]
    }
  },
  created() {
    this.init();
    this.getCategories()
    this.getLocations()
    this.getGoods()
    this.getMember()
  },
  methods: {
    getNextDate(date, day = 1, format = "{y}-{m}-{d}") {
      if (date) {
        const nDate = new Date(date);
        nDate.setDate(nDate.getDate() + day);

        const formatObj = {
          y: nDate.getFullYear(),
          m: nDate.getMonth() + 1,
          d: nDate.getDate(),
        };
        return format.replace(/{([ymd])+}/g, (result, key) => {
          const value = formatObj[key];
          return value.toString().padStart(2, "0");
        });
      } else {
        throw new Error("getNextDate:错误的参数");
      }
    },
    inputDays(val) {
      this.dataForm.days = val;
      this.value1 = undefined;
      this.dataForm.startTime = undefined;
      this.dataForm.endTime = undefined;
      // const now = new Date();
      // const endTime = this.getNextDate(now.toJSON().substr(0, 10), +val) + ' 00:00:00';
      // const startTime = now.toJSON().substr(0, 10) + ' 00:00:00';
      // this.value1 = [startTime, endTime];
    },
    changeDatePick(val) {
      if (val) {
        const [start, end] = val;
        // console.log(val);
        // const date1 = new Date(start).getTime();
        // const date2 = new Date(end).getTime();
        // let day = Math.abs(date1 - date2);
        // day = day / (1000 * 60 * 60 * 24);
        this.dataForm.startTime = start;
        this.dataForm.endTime = end;
        // this.$set(this.dataForm, 'days', day);
      } else {
        this.dataForm.startTime = undefined;
        this.dataForm.endTime = undefined;
      }
      this.days = undefined;
      this.dataForm.days = undefined;
    },
    changeIsBirthdayUse(val) {
      this.dataForm.isBirthdayUse = val;
    },
    changeDateTime(val) {
      const [startTime, endTime] = val;
      this.dataForm.startTime = startTime;
      this.dataForm.endTime = endTime;
    },
    changeCheckbox(val, $event) {
      const target = $event.target.value;
      if (target == 0) {
        if (val) {
          this.checkList = ['0', '1', '2', '3'];
        }
        else {
          this.checkList = [];
        }
      } else {
        if (this.checkList.length == 3) {
          const allCheck = this.checkList.findIndex(item => item == '0');
          if (allCheck != -1) {
            this.checkList.shift();
          }
          else {
            this.checkList.unshift('0');
          }
        }
      }
    },
    formatStatus(status) {
      if (status === 0) {
        return this.$t('新增')
      } else if (status === 1) {
        return this.$t('已上架')
      } else {
        return this.$t('已下架')
      }
    },
    init: function () {
      // this.$refs.dataForm.resetFields();
      try {
        if (this.$route.query.dataForm) {
          this.dataForm = { ...this.$route.query.dataForm };
        }
        if (this.dataForm.startTime) {
          this.isBirthdayUse = this.dataForm.isBirthdayUse;
        } else {
          this.isBirthdayUse = 0;
        }
        if (this.dataForm.days) {
          this.radio = 1;
        }
        this.checkList = ['1'];
        // this.checkList = this.dataForm.ranges.join(',').split(',') || [];
        this.checkList = this.dataForm.ranges.map(item => item + '');
        this.dialogFormVisible = this.$route.query.dialogFormVisible
        this.dialogStatus = this.$route.query.dialogStatus
        if (this.dataForm.startTime) {
          this.value1 = [this.dataForm.startTime, this.dataForm.endTime];
        }
        if (this.dataForm.days) {
          this.inputDays(this.dataForm.days);
        }
        this.days = this.dataForm.days;
      } catch (e) { }

    },
    getCategories() {
      listCategory().then(response => {
        this.categories = response.data.data.list
        if (this.dataForm.goodsValue && this.dataForm.goodsValue.length > 0) {
          let p = [];
          this.dataForm.goodsValue.forEach(goodsId => {
            this.categories.forEach(category => {
              if (category.children && category.children.length > 0) {
                category.children.forEach(item => {
                  if (item.children && item.children.length > 0) {
                    item.children.forEach(sub => {
                      if (sub.id == goodsId) {
                        let tmp = sub.id;
                        p.push(tmp)
                      }
                    })
                  }
                })
              }
            })
          })
          this.dataForm.goodsValue = p;
        }
      })
    },
    getLocations() {
      listLocationRegion().then(response => {
        this.locations = response.data.data.list
        if (this.dataForm.regions && this.dataForm.regions.length > 0) {
          let p = [];
          this.dataForm.regions.forEach(id => {
            this.locations.forEach(region => {
              if (region.children && region.children.length > 0) {
                region.children.forEach(item => {
                  if (item.children && item.children.length > 0) {
                    item.children.forEach(sub => {
                      if (sub.id == id) {
                        let tmp = sub.id;
                        p.push(tmp)
                      }
                    })
                  }
                })
              }
            })
          })
        }
      })

    },
    getGoods() {
      this.listLoading = true
      listpPutaway(this.listGoodsQuery).then(response => {
        this.goodsList = response.data.data.list.map(goods => {
          return {
            label: goods.name,
            key: goods.id
          }
        })
      }).catch(() => {
        this.list = []
      })
    },
    handleBack() {
      this.$router.push({ path: '/coupon/elecCoupon' })
    },
    createData() {
      if (this.checkList.length == 0) {
        this.$message.error(this.$t('请选择使用范围'));
        return;
      }
      // if (this.dataForm.timeType == 1) {
      //   if (!this.dataForm.timeList || this.dataForm.timeList.length == 0) {
      //     this.$message.error(this.$t('请选择指定绝对时间'));
      //     return;
      //   }
      // }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataForm.discountType == 2) {
            let p = [];
            this.dataForm.goodsValue.forEach(goodsId => {
              p.push(goodsId)
            })
            this.dataForm.goodsValue = p;
          }
          if (this.dataForm.selectGoods.length != 0 && this.dataForm.goodsType === 2) {
            for (let i = 0; i < this.dataForm.selectGoods.length; i++) {
              this.dataForm.goodsValue[i] = this.dataForm.selectGoods[i]
            }
          }
          // this.dataForm.ranges = this.checkList.filter(item => item != 0).join(',');
          this.dataForm.ranges = this.checkList.length == 4 ? ['0'] : this.checkList;
          this.dataForm.surplus = this.dataForm.total
          this.$router.push({ path: '/coupon/elecCoupon' })
          createCoupon(this.dataForm)
            .then(response => {
              this.$notify.success({
                title: this.$t('Success!'),
                message: this.$t('Coupon_creation_successful')
              })

            })
            .catch(response => {
              this.$notify.error({
                title: this.$t('Failed'),
                message: this.$t(response.data.errmsg)
              })
            })
        }
      })
    },
    updateData() {
      if (this.checkList.length == 0) {
        this.$message.error(this.$t('请选择使用范围'));
        return;
      }
      // if (this.dataForm.timeType == 1) {
      //   if (!this.dataForm.timeList || this.dataForm.timeList.length == 0) {
      //     this.$message.error(this.$t('请选择指定绝对时间'));
      //     return;
      //   }
      // }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataForm.discountType == 2) {
            let p = [];
            this.dataForm.goodsValue.forEach(goodsId => {
              p.push(goodsId[2])
            })
            this.dataForm.goodsValue = p;
          }
          if (this.dataForm.selectGoods.length != 0 && this.dataForm.goodsType === 2) {
            this.dataForm.goodsValue = [];
            for (let i = 0; i < this.dataForm.selectGoods.length; i++) {
              this.dataForm.goodsValue[i] = this.dataForm.selectGoods[i]
            }
          }
          // this.dataForm.ranges = this.checkList.filter(item => item != 0).join(',');
          this.dataForm.ranges = this.checkList.length == 4 ? ['0'] : this.checkList;
          this.dataForm.surplus = this.dataForm.total
          updateCoupon(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: this.$t('Success!'),
                message: this.$t('Coupon_update_successful')
              })

              this.$router.push({ path: '/coupon/elecCoupon' })
            })
            .catch(response => {
              this.$notify.error({
                title: this.$t('Failed'),
                message: this.$t(response.data.errmsg)
              })
            })
        }
      })
    },
    uploadPicUrl: function (response) {
      this.dataForm.pictureUrl = response.data.url
    },
    handleGoodsPicRemove: function () {
      this.dataForm.pictureUrl = undefined
    },
    changeLevelMember(obj) {
      this.isLevelMember = !this.isLevelMember
    },
    changeMoneyMember(obj) {
      this.isMoneyMember = !this.isMoneyMember
    },
    changeNum(num) {
      if (num < 0) {
        this.$message.warning(this.$t('禁止输入小数以及负数'))
        this.dataForm.useLimitNum = 1;
      }
    },
    handleChangeType() {
      if (this.dataForm.type == 3) {
        this.dataForm.userLevel = [0]
        this.dataForm.promotionOnly = false
        this.dataForm.timeType = 1
        this.dataForm.goodsType = 0
      }
    },
    getMember() {
      var data = {
        page: 1,
        limit: 10000,
        status: 2
      }

      var dataLevel = {
        page: 1,
        limit: 10000,
        status: 2,
      }

      payMemberList(data).then(response => {
        this.moneyMember = response.data.data.list
        this.listLoading = false
      }).catch(() => {
        this.moneyMember = []
        this.listLoading = false
      })

      levelMemberList(dataLevel).then(response => {
        this.levelMember = response.data.data.list
        this.listLoading = false
      }).catch(() => {
        this.levelMember = []
        this.listLoading = false
      })
    },
    // getDatePickerShow() {
    //   if (this.typePage) {
    //     return true;
    //   } else {
    //     if(this.value1) {
    //       return true
    //     } else {
    //       return false;
    //     }
    //   }
    // },
    // getDaysShow(){
    //   if (this.typePage) {
    //     return true;
    //   } else {
    //     if( typeof this.days != 'undefined') {
    //       return true;
    //     }else{
    //       return false;
    //     }
    //   }
    // },
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    },
    typePage() {
      return this.$route.query.dialogStatus == 'create'
    }
  }
}
</script>

<style scoped>
/deep/ input::-webkit-inner-spin-button,
/deep/ input::-webkit-outer-spin-button {
  -webkit-appearance: none !important;
}

/deep/ input[type="number"] {
  -moz-appearance: textfield;
}
</style>

